package com.service;

import com.config.MQConfig;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MianshaServicce {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private MQService mqService;

    /**
     * 秒杀
     * @param uid 用户编号
     * @param goodsId 商品编号
     * @return
     */
    public String miaosha(String uid,String goodsId) throws InterruptedException {

        //如果秒杀过了就不能秒杀了
        Object user = redisTemplate.boundValueOps(uid + "::" + goodsId);

        if (user!=null){
            return "已经秒杀过了";
        }

        //加锁
        RLock rLock=redissonClient.getLock("miaosha");
        boolean f=rLock.tryLock(300,1000, TimeUnit.MILLISECONDS);
            if (f==false){
                return "当前访问用户太多，请等一会再试";
            }

            //判断库存
//        List goodsList= (List) redisTemplate.boundListOps("goods");

            Integer goods= (Integer) redisTemplate.boundValueOps("goods").get();

            if (goods==null){
                return "秒杀商品不存在";
            }
            if (goods<0){
                return "库存不足";
            }


            //秒杀成功
        goods--;
            redisTemplate.boundValueOps("goods").set(goods);
            redisTemplate.boundValueOps(uid+"::"+goodsId).set("ok",1,TimeUnit.HOURS);

            String msg=String.format("{goods:'%s',uid:'%s'}",goodsId,uid);
            mqService.sendMessage(MQConfig.DIRECT_ECHANGE,MQConfig.KEY_MIAOSHA,msg);
            return "秒杀成功";

    }

}
